﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml;

using Models;

using Panuon.UI.Silver;

using Taxhui.Utils.CryptUtils;

namespace Client.Common
{
    public static class Comm
    {
        public static UserModel UserInfo;
        public static ConfigModel CFG;
        public static Window Shell;
        public static NetClient NetCtrl = new NetClient();
        public static bool Running = true;

        private static string _cfgPath = Environment.CurrentDirectory + @"\Config.xml";

        static Comm()
        {
            CFG = new ConfigModel();
            UserInfo = null;
        }

        #region 重新创建配置文件

        public static void RebuildConfig()
        {
            XmlDocument xDoc = new XmlDocument();
            XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xDoc.AppendChild(xDec);
            XmlElement root = xDoc.CreateElement("ROOT");
            XmlElement cfg = xDoc.CreateElement("LoginConfig");
            //登录参数
            cfg.AppendChild(CreateElement(xDoc, "IsSavePass", CFG.IsSavePass ? "True" : "False"));
            cfg.AppendChild(CreateElement(xDoc, "SavedUser", CFG.SavedUser));
            cfg.AppendChild(CreateElement(xDoc, "SavedPass", CFG.SavedPass));
            root.AppendChild(cfg);
            cfg = xDoc.CreateElement("RemoteConfig");
            cfg.AppendChild(CreateElement(xDoc, "ServerAddr", CFG.ServerAddr));
            cfg.AppendChild(CreateElement(xDoc, "ServerPort", CFG.ServerPort.ToString()));
            root.AppendChild(cfg);
            //根节点
            xDoc.AppendChild(root);
            string docStr = xDoc.OuterXml;
            docStr = DESCrypt.DESEncrypt(docStr, "a995211b", "sbi.*008");
            FileStream fs = new FileStream(_cfgPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            byte[] buffer = Encoding.UTF32.GetBytes(docStr);
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();
            fs.Dispose();
        }

        private static XmlElement CreateElement(XmlDocument doc, string name, string txt)
        {
            XmlElement xl = doc.CreateElement(name);
            xl.InnerText = txt;
            return xl;
        }

        #endregion 重新创建配置文件

        #region 读取配置

        public static void ReadConfig()
        {
            try
            {
                CFG = new ConfigModel
                {
                    IsSavePass = false,
                    SavedPass = "",
                    SavedUser = ""
                };
                if (!File.Exists(_cfgPath))
                    RebuildConfig();
                System.Threading.Thread.Sleep(100);
                XmlDocument doc = new XmlDocument();
                FileStream fs = new FileStream(_cfgPath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                fs.Dispose();
                string enStr = Encoding.UTF32.GetString(buffer);
                string xml = DESCrypt.DESDecrypt(enStr, "a995211b", "sbi.*008");
                doc.LoadXml(xml);
                XmlNode root = doc.SelectSingleNode("ROOT");
                if (null == root)
                {
                    RebuildConfig();
                    return;
                }
                XmlNode node = root.SelectSingleNode("LoginConfig");
                CFG.IsSavePass = Convert.ToBoolean(node.SelectSingleNode("IsSavePass")?.InnerText);
                CFG.SavedPass = node.SelectSingleNode("SavedPass")?.InnerText;
                CFG.SavedUser = node.SelectSingleNode("SavedUser")?.InnerText;
                node = root.SelectSingleNode("RemoteConfig");
                CFG.ServerAddr = node.SelectSingleNode("ServerAddr")?.InnerText;
                CFG.ServerPort = Convert.ToInt32(node.SelectSingleNode("ServerPort")?.InnerText);
            }
            catch (Exception)
            {
                RebuildConfig();
            }
        }

        #endregion 读取配置

        #region 保存配置文件

        public static void SaveConfig()
        {
            RebuildConfig();
        }

        #endregion 保存配置文件

        #region 显示提示框

        public static void ShowErr(string mess, string title, MessageBoxIcon mi = MessageBoxIcon.Error)
        {
            MessageBoxX.Show(mess, title, Shell, MessageBoxButton.OK, new MessageBoxXConfigurations()
            {
                MessageBoxIcon = mi,
                MaxContentHeight = 400,
                MaxContentWidth = 600,
                MessageBoxStyle = MessageBoxStyle.Modern,
                MinHeight = 200,
                MinWidth = 300,
                OKButton = "确定",
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Topmost = false
            });
        }

        #endregion 显示提示框

        #region 返回一个带 ReqId的dc

        public static Dictionary<string, object> GetDC()
        {
            Dictionary<string, object> dc = new Dictionary<string, object>
            {
                ["sessionId"] = UserInfo?.SessionId,
                ["reqId"] = Guid.NewGuid().ToString()
            };
            return dc;
        }

        #endregion 返回一个带 ReqId的dc
    }
}